<?php
/**
 * Created by PhpStorm.
 * User: XT
 * Date: 2017/4/17
 * Time: 9:47
 */
namespace core;

use core\http\Request;

class View {

    protected $_assign =  [];
    protected static $instance = [];
    protected $template = '';

    /**
     * @param string $template
     * @param array $params
     * @return static
     */
    public static function getInstance($template = '', $params = [])
    {
        $key = md5($template);
        if (!isset(self::$instance[$key])) {
            self::$instance[$key] = new static($template, $params);
        }
        return self::$instance[$key];
    }

    /**
     * View constructor.
     * @param string $template
     * @param array $params
     */
    public function __construct($template = '', array $params = [])
    {
        $this->assign($params);
        $this->template = $template;
    }

    /**
     * @param $name
     * @param string $value
     */
    private function assign($name, $value = '')
    {
        if(is_array($name)) {
            foreach ($name as $k => $v) {
                $this->_assign[$k] = $v;
            }
        } else {
            $this->_assign[$name] = $value;
        }
    }

    /**
     * 渲染模板
     * @param string $template
     */
    private function display($template = '')
    {
        @extract($this->_assign);
        $file_path = $this->getTemplate($template);
        include $file_path . '';
    }

    /**
     * 获取模板位置
     * @param string $template
     * @return string
     */
    private function getTemplate($template = '')
    {
        $request = Request::getInstance();
        if (empty($template)) {
            if (empty($this->template)) {
                $template = $request->action();
            } else {
                $template = $this->template;
            }
        }
        $this->template = $template;
        $file_path = APP_PATH . $request->module() . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR .
            $request->controller() . DIRECTORY_SEPARATOR . $this->template . '.tpl.php';
        return $file_path;
    }

    /**
     * 返回模板信息
     * @param string $template
     * @param array $params
     * @return string
     */
    public function fetch($template = '', $params = [])
    {
        $this->assign($params);
        $this->display($template);
    }
}